package com.guaoran.source.zookeeper.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/12 17:54
 */
public class ConnectionDemo {
    public static void main(String[] args) {
        /**
         *
            Zookeeper:
                1.同级节点唯一性
                2.节点包含有序、临时、持久化
                3.临时节点不能创建子节点
                4.创建和删除不能删除父节点和子节点，只能一级一级的创建和删除

         */

        final CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            ZooKeeper zooKeeper =
                    new ZooKeeper("192.168.45.131:2181,192.168.45.133:2181,192.168.45.134:2181", 4000, new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            if(Event.KeeperState.SyncConnected==event.getState()){
                                //如果是连接响应
                                countDownLatch.countDown();
                            }
                        }
                    });
            System.out.println(zooKeeper.getState());
            countDownLatch.await();
            System.out.println(zooKeeper.getState());
            //创建节点,开放式的ACL,,持久化节点
            zooKeeper.create("/demo", "demo".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            Stat stat = new Stat();
            byte[] data = zooKeeper.getData("/demo", null, stat);
            System.out.println(new String(data));
            System.out.println(stat);
            //设置值
            zooKeeper.setData("/demo","guaoran".getBytes(),stat.getVersion());
            data = zooKeeper.getData("/demo", null, stat);
            System.out.println(new String(data));
            zooKeeper.delete("/demo",stat.getVersion());
            //-1代表强制删除
            //zooKeeper.delete("/demo",-1);
            zooKeeper.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }
}
